<?php

namespace App\Models;

use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
use DateTimeInterface;

class Crm_Order extends Model implements AuthenticatableContract, AuthorizableContract
{
    use Authenticatable, Authorizable, HasFactory;

    /**
     * 关联到模型的数据表
     *
     * @var string
     */
    protected $table = 'crm_order';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'agencyid',
        'ordersn',
        'mid',
        'realname',
        'mobile',
        'idcard',
        'package_name',
        'price',
        'days',
        'nums',
        'signdate',
        'startdate',
        'enddate',
        'belongid',
        'serviceid',
        'inviteid',
        'remark',
        'order_status'
    ];

    public static function _generateSn($prefix,$aid)
    {
        list($usec, $sec) = explode(' ', microtime());
        return $prefix . $aid . date('YmdHis', $sec) . substr($usec, 3, 2);
    }

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function hasOneContract()
    {
        return $this->hasOne('App\Models\Crm_Contract', 'oid', 'id');
    }

    public function hasManyPayment()
    {
        return $this->hasMany('App\Models\Crm_Order_Payment', 'oid', 'id');
    }

    public function hasManyRefund()
    {
        return $this->hasMany('App\Models\Crm_Order_Refund', 'oid', 'id');
    }

    public static function getFilter($filter)
    {
        return self::where(function ($query) use ($filter){
            if ($filter['type'] == 1 && !empty($filter['keyword'])) {
                $query->where('mid',  $filter['keyword'] );
            }
            if ($filter['type'] == 2 && !empty($filter['keyword'])) {
                $query->where('mobile', 'LIKE', '%' . $filter['keyword'] . '%');
            }
            if ($filter['type'] == 3 && !empty($filter['keyword'])) {
                $query->where('realname', 'LIKE', '%' . $filter['keyword'] . '%');
            }
            if (!empty($filter['belongid'])) {
                $query->where('belongid',  $filter['belongid'] );
            }
            if (!empty($filter['serviceid'])) {
                $query->where('serviceid',  $filter['serviceid'] );
            }
            $query->where('agencyid', $filter['aid']);
        })->orderBy('id', 'desc');
    }

}
